package com.yjf.ljr.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yjf.ljr.R;
import com.yjf.ljr.activity.MyAccountActivity;
import com.yjf.ljr.activity.MyInvestActivity;
import com.yjf.ljr.activity.ProjectDetailActivity;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.AppinvestDataClass;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;

public class AppInvestDialog extends Dialog {

	public AppInvestDialog(Context context) {
		super(context);

	}

	public AppInvestDialog(Context context, int theme) {
		super(context, theme);
	}

	public static class Builder {
		private Context context;
		private String title;
		private String paypassUrl;
		// private CookieManager mCookieManager;
		private String token;
		private String tradeId;// 当前项目的tradeID
		private String demandId;// 项目ID
		private String giftTradeId;// 加息券ID
		private String amount;// 投资金额

		// add red packet and experience amount
		private String giftMoney;// 红包
		private String experienceAmount;// 体验金

		private String positiveButtonText;
		private String negativeButtonText;
		private View contentView;
		private ProgressBar mProgressBar;
		private LinearLayout mLlllInvest_pay_blank;
		private WebView mwebView;
		private DialogInterface.OnClickListener positiveButtonClickListener;
		private DialogInterface.OnClickListener negativeButtonClickListener;
		private boolean resultFlag = false;
		private CookieManager mCookieManager;

		private boolean showProgress = false;

		private boolean isNewerInvest = false;

		public Builder(Context context) {
			this.context = context;

		}

		public Builder setPaypassUrl(String paypassUrl) {
			this.paypassUrl = paypassUrl;
			resultFlag = false;
			return this;
		}

		/**
		 * Set the Dialog message from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setPaypassUrl(int paypassUrl) {
			this.paypassUrl = (String) context.getText(paypassUrl);
			return this;
		}

		public Builder setAmount(String amount) {
			this.amount = amount;
			return this;
		}

		public Builder setAmount(int amount) {
			this.amount = (String) context.getText(amount);
			return this;
		}

		public Builder setToken(String token) {
			this.token = token;

			return this;
		}

		public Builder setToken(int token) {
			this.token = (String) context.getText(token);
			return this;
		}

		public Builder setTradeId(String tradeId) {
			this.tradeId = tradeId;

			return this;
		}

		public Builder setTradeId(int tradeId) {
			this.tradeId = (String) context.getText(tradeId);
			return this;
		}

		public Builder setDemandId(String demandId) {
			this.demandId = demandId;

			return this;
		}

		public Builder setDemandId(int demandId) {
			this.demandId = (String) context.getText(demandId);
			return this;
		}

		// 加息券ID
		public Builder setGiftTradeId(String giftTradeId) {
			this.giftTradeId = giftTradeId;

			return this;
		}

		public Builder setGiftTradeId(int giftTradeId) {
			this.giftTradeId = (String) context.getText(giftTradeId);
			return this;
		}

		/**
		 * set red packet amount
		 * 
		 * @param giftMoney
		 * @return
		 */
		public Builder setGiftMoney(String giftMoney) {
			this.giftMoney = giftMoney;
			return this;
		}

		/**
		 * set experience amount
		 * 
		 * @param experienceAmount
		 * @return
		 */
		public Builder setExperienceAmount(String experienceAmount) {
			this.experienceAmount = experienceAmount;
			return this;
		}

		public Builder setIsNewerInvest(boolean isNewerInvest) {
			this.isNewerInvest = isNewerInvest;
			return this;
		}

		/**
		 * Set the Dialog title from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setTitle(int title) {
			this.title = (String) context.getText(title);
			return this;
		}

		/**
		 * Set the Dialog title from String
		 * 
		 * @param title
		 * @return
		 */

		public Builder setTitle(String title) {
			this.title = title;
			return this;
		}

		public Builder setContentView(View v) {
			this.contentView = v;
			return this;
		}

		/**************** 得到屏幕高度 *******************/

		/**
		 * Set the positive button resource and it's listener
		 * 
		 * @param positiveButtonText
		 * @return
		 */
		public Builder setPositiveButton(int positiveButtonText, DialogInterface.OnClickListener listener) {
			this.positiveButtonText = (String) context.getText(positiveButtonText);
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) {
			this.positiveButtonText = positiveButtonText;
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(int negativeButtonText, DialogInterface.OnClickListener listener) {
			this.negativeButtonText = (String) context.getText(negativeButtonText);
			this.negativeButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) {
			this.negativeButtonText = negativeButtonText;
			this.negativeButtonClickListener = listener;
			return this;
		}

		String cookieString;

		@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
		public AppInvestDialog create() {
			showProgress = false;
			/***************************/
			if (Build.VERSION.SDK_INT >= 11) {
				StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
						.detectNetwork().penaltyLog().build());
				StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
						.detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
			}

			/***************************/

			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			// instantiate the dialog with the custom Theme
			final AppInvestDialog dialog = new AppInvestDialog(context, R.style.Dialog);
			View layout = inflater.inflate(R.layout.activity_appinvest_dialog, null);
			dialog.addContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			// set the dialog title
			((TextView) layout.findViewById(R.id.tvAppInvesttitle)).setText(title);
			mwebView = ((WebView) layout.findViewById(R.id.wvAppInvestPaymentCipher));
			mLlllInvest_pay_blank = ((LinearLayout) layout.findViewById(R.id.llInvest_pay_blank));
			TextView message = (TextView) layout.findViewById(R.id.invest_message);
			double amountD = AppUtil.moneyToNum(amount);
			double giftMoneyD = AppUtil.moneyToNum(giftMoney);
			double experienceAmountD = AppUtil.moneyToNum(experienceAmount);
			double realAmountD = amountD - giftMoneyD - experienceAmountD;
			String realAmount = AppUtil.getAmountString("" + realAmountD, null);
			message.setText(context.getString(R.string.invest_real_amount, realAmount));

			mProgressBar = ((ProgressBar) layout.findViewById(R.id.appInvestprogressBar));
			// set the confirm button
			if (positiveButtonText != null) {
				((Button) layout.findViewById(R.id.positiveButton)).setText(positiveButtonText);
				if (positiveButtonClickListener != null) {
					((Button) layout.findViewById(R.id.positiveButton)).setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							positiveButtonClickListener.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
						}
					});
				}
			} else {
				// if no confirm button just set the visibility to GONE
				layout.findViewById(R.id.positiveButton).setVisibility(View.GONE);
			}
			// set the cancel button
			if (negativeButtonText != null) {
				((Button) layout.findViewById(R.id.negativeButton)).setText(negativeButtonText);
				if (negativeButtonClickListener != null) {
					((Button) layout.findViewById(R.id.negativeButton)).setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							negativeButtonClickListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE);
						}
					});
				}
			} else {
				// if no confirm button just set the visibility to GONE
				layout.findViewById(R.id.negativeButton).setVisibility(View.GONE);
			}

			// set the content message
			if (paypassUrl != null) {

				WebSettings settings = mwebView.getSettings();
				mwebView.loadUrl(paypassUrl);

				int scale = (int) context.getResources().getDimension(R.dimen.webview_scale);
				mwebView.setInitialScale(scale);
				mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
				settings.setSupportZoom(false);
				settings.setBuiltInZoomControls(false);
				settings.setDomStorageEnabled(true);

				settings.setAllowFileAccess(true);

				settings.setAppCacheEnabled(true);

				settings.setJavaScriptEnabled(true);
				mwebView.getSettings().setUseWideViewPort(true);
				settings.setCacheMode(WebSettings.LOAD_DEFAULT);

				settings.setUseWideViewPort(false);
				settings.setLoadWithOverviewMode(false);
				settings.supportMultipleWindows();
				settings.setDatabaseEnabled(true);
				CookieSyncManager.createInstance(context);
				settings.setJavaScriptCanOpenWindowsAutomatically(true);

				/*******************/
				mwebView.setWebChromeClient(new WebChromeClient());

				mwebView.setWebViewClient(new WebViewClient() {

					@Override
					public void onPageFinished(WebView view, String url) {
						// TODO Auto-generated method stub

						int pagefinishResult = url.indexOf("isSuccess=true");
						resultFlag = true;
						/*
						 * if (!resultFlag) {
						 * mProgressBar.setVisibility(View.GONE); }
						 */
						// if (-1 != pagefinishResult) {
						// dialog.dismiss();
						// // mProgressBar.setVisibility(View.GONE);
						//
						// // MyInvestActivity.instance.finish();
						//
						// }
						if (!showProgress) {
							mProgressBar.setVisibility(View.GONE);
							mLlllInvest_pay_blank.setVisibility(View.GONE);
						}
						if (MyInvestActivity.mDialogFlag) {
							MyInvestActivity.mDialogFlag = false;
							mwebView.clearCache(true);
							mwebView.clearHistory();
						} else {
							mwebView.clearCache(true);
							mwebView.clearHistory();
							super.onPageFinished(view, url);
						}
					}

					@Override
					public void onPageStarted(WebView view, String url, Bitmap favicon) {
						// TODO Auto-generated method stub
						super.onPageStarted(view, url, favicon);
						/*
						 * CookieSyncManager.createInstance(context);
						 * mCookieManager = CookieManager.getInstance();
						 * cookieString = mCookieManager.getCookie(url);
						 */
						mProgressBar.setVisibility(View.VISIBLE);
						int cancelResult = url.indexOf("yjfPayPassewordCancelUrl");
						int ReturnResult = url.indexOf("yjfPayPassewordReturnUrl");
						int determineResult = url.indexOf("isSuccess=true");
						String mFailStr = null;
						AppinvestDataClass dc = new AppinvestDataClass();
						if (-1 != cancelResult && -1 == ReturnResult && resultFlag) {
							dialog.dismiss();

						} else if (-1 != determineResult && -1 == cancelResult) {
							showProgress = true;
							mProgressBar.setVisibility(View.VISIBLE);
							String paytk = "";
							int startIndex = url.indexOf("paytk=");
							int endIndex = url.indexOf("&_t");
							if (!TextUtils.isEmpty(url) && startIndex != -1 && endIndex != -1) {
								paytk = url.substring(startIndex + 6, endIndex).toString();

								// new RechargeTestTask(bankCode,
								// rechargeAmount, paytk, token,
								// dialog).execute();
								// TODO Auto-generated method stub
								resultFlag = true;
								mwebView.stopLoading();
								new InvestPasswordTask(tradeId, demandId, paytk, token, amount, giftMoney,
										experienceAmount, dialog, isNewerInvest).execute();

								// RequestObject requestObject = new
								// RequestObject();
								// requestObject.method = "appInvest";
								// requestObject.map.put("tradeId", tradeId);
								// requestObject.map.put("demandId", demandId);
								// requestObject.map.put("paytk", paytk);
								// requestObject.map.put("token", token);
								// requestObject.map.put("amount", amount);
								// //add red packet and experience amount
								// if(!TextUtils.isEmpty(giftMoney))
								// requestObject.map.put("giftMoney",
								// giftMoney);
								// if(!TextUtils.isEmpty(experienceAmount))
								// requestObject.map.put("experienceAmount",
								// experienceAmount);
								//
								// String requrestUrl =
								// RequestBuilder.build(requestObject);
								// resultFlag = true;
								// try {
								// IjConnect.doRequest(requrestUrl, dc);
								//
								// if (dc.code == null) {
								// mFailStr = "获取数据异常，请稍后重试";
								// } else if
								// (!dc.code.equals(CommonData.RESULT_SUCCESS))
								// {
								// mFailStr = dc.msg;
								// }
								// } catch (Exception e) {
								// mFailStr = "获取数据异常，请稍后重试";
								// e.printStackTrace();
								// }
								//
								// if (!(TextUtils.isEmpty(mFailStr))) {// fail
								// Toast.makeText(context, mFailStr,
								// Toast.LENGTH_LONG).show();
								// // RechargeActivity.mDialogFlag = true;
								// // RechargeActivity.mResult = mFailStr;
								// MyInvestActivity.instance.finish();
								// dialog.dismiss();
								// } else {// success
								// Toast.makeText(context, dc.msg,
								// Toast.LENGTH_LONG).show();
								// if(dc.giftMoney != null &&
								// "1".equals(dc.giftMoney)) {
								// dialog.dismiss();
								// MyInvestActivity.instance.showRedPacketDialog(dc);
								// } else {
								// MyInvestActivity.mDialogFlag = true;
								// ProjectDetailActivity.AppInvestDialgFlag =
								// true;
								// ProjectDetailActivity.AppInvestDialgProgress
								// = dc.investProgress;
								// dialog.dismiss();
								// MyInvestActivity.instance.finish();
								// }
								// }
							}
						}
					}
				});

			} else if (contentView != null) {
				// if no message set // add the contentView to the dialog body
				((WebView) layout.findViewById(R.id.wvAppInvestPaymentCipher)).removeAllViews();
				((WebView) layout.findViewById(R.id.wvAppInvestPaymentCipher)).addView(contentView,
						new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			}

			dialog.setContentView(layout);
			return dialog;
		}

		class InvestPasswordTask extends AsyncTask<Void, Void, Void> {

			private String mFailStr = null;
			private AppinvestDataClass dc = new AppinvestDataClass();
			private String tradeId;
			private String demandId;
			private String paytk;
			private String token;
			private String amount;
			private String giftMoney;
			private String experienceAmount;
			private AppInvestDialog dialog;
			private boolean isNewerInvest;

			public InvestPasswordTask(String tradeId, String demandId, String paytk, String token, String amount,
					String giftMoney, String experienceAmount, AppInvestDialog dialog, boolean isNewerInvest) {
				this.tradeId = tradeId;
				this.demandId = demandId;
				this.paytk = paytk;
				this.token = token;
				this.amount = amount;
				this.giftMoney = giftMoney;
				this.experienceAmount = experienceAmount;
				this.dialog = dialog;
				this.isNewerInvest = isNewerInvest;
			}

			@Override
			protected Void doInBackground(Void... params) {
				RequestObject requestObject = new RequestObject();
				if (isNewerInvest) {
					requestObject.method = "newerInvest";
				} else {
					requestObject.method = "appInvest";
					// add red packet and experience amount
					if (!TextUtils.isEmpty(giftMoney))
						requestObject.map.put("giftMoney", giftMoney);
					if (!TextUtils.isEmpty(experienceAmount))
						requestObject.map.put("experienceAmount", experienceAmount);
				}
				requestObject.map.put("tradeId", tradeId);
				requestObject.map.put("demandId", demandId);
				requestObject.map.put("paytk", paytk);
				requestObject.map.put("token", token);
				requestObject.map.put("amount", amount);
				requestObject.map.put("gainMoneyTradeIds", giftTradeId);// 加息券id

				String requrestUrl = RequestBuilder.build(requestObject);
				try {
					IjConnect.doRequest(requrestUrl, dc);

					if (dc.code == null) {
						mFailStr = "获取数据异常，请稍后重试";
					} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
						mFailStr = dc.msg;
					}
				} catch (Exception e) {
					mFailStr = "获取数据异常，请稍后重试";
					e.printStackTrace();
				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (!(TextUtils.isEmpty(mFailStr))) {// fail
					Toast.makeText(context, mFailStr, Toast.LENGTH_LONG).show();
					MyInvestActivity.instance.finish();
					dialog.dismiss();
				} else {// success

					Toast.makeText(context, dc.msg, Toast.LENGTH_LONG).show();
					if (dc.giftMoney != null && "1".equals(dc.giftMoney)) {
						dialog.dismiss();
						MyInvestActivity.instance.showRedPacketDialog(dc);
					} else {
						MyAccountActivity.isNeedFresh = true;
						MyInvestActivity.mDialogFlag = true;
						ProjectDetailActivity.AppInvestDialgFlag = true;
						ProjectDetailActivity.AppInvestDialgProgress = dc.investProgress;
						Intent intent = new Intent();
						intent.putExtra("investProgress", dc.investProgress);
						MyInvestActivity.instance.setResult(Activity.RESULT_OK, intent);
						MyInvestActivity.instance.finish();
						dialog.dismiss();
					}
				}
			}

		}

	}

}
